package com.xpec.c4.db.dao.global;


import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.xpec.c4.db.basic.BasicLogDAO;
import com.xpec.c4.db.hibernate.manager.HibernateLogManager;
import com.xpec.c4.db.model.global.DBIpFilterModel;

public class IpFilterDAO extends BasicLogDAO {


	/**
	 * 
	 * @param rule
	 * @param ip
	 * @param ipRang
	 * @param allowStatus
	 * @return
	 */
	public static boolean save(String name, String rule, String remark,
			int allowStatus, boolean disable) {
		
//		Session session = HibernateManager.getSession();
//		Criteria criteria = session.createCriteria(DBIpFilterModel.class);
		
		// log.info("db savePlayer:" + player);
		
		DBIpFilterModel model = null;
		try{
			model = loadByName(name);
		}catch(Exception e){
			
		}
		
		if(model != null){
			try{
				model.setRule(rule);
				model.setName(name);
				model.setRemark(remark);
				model.setStatus(allowStatus);
				model.setDisable(disable);
				
				HibernateLogManager.txBegin();
				update(model);
				return HibernateLogManager.txCommitFailRollbackClearSession();
			}
			catch(HibernateException e){
				boolean res = HibernateLogManager.txRollback();
				HibernateLogManager.endSession();
				return res;
			}
			
		}else{
			model = new DBIpFilterModel();
			model.setRule(rule);
			model.setName(name);
			model.setRemark(remark);
			model.setStatus(allowStatus);
			model.setDisable(disable);
			try{
				HibernateLogManager.txBegin();
				save(model);
				return HibernateLogManager.txCommitFailRollbackClearSession();
			}
			catch(HibernateException e){
				boolean res = HibernateLogManager.txRollback();
				HibernateLogManager.endSession();
				return res;
			}
		}

	}

	/**
	 * 
	 * @param name
	 * @return
	 */
	public static DBIpFilterModel loadByName(String name) {
		Session session = HibernateLogManager.getSession();
		Criteria criteria = session.createCriteria(DBIpFilterModel.class);
		criteria.add(Restrictions.eq("name", name));		
		DBIpFilterModel model = (DBIpFilterModel) criteria.uniqueResult();		
		HibernateLogManager.endSession();
		
		if (model != null) {
			DBIpFilterModel data = new DBIpFilterModel();
			data.setDisable(model.isDisable());
			data.setId(model.getId());
			data.setName(model.getName());
			data.setRemark(model.getRemark());
			data.setRule(model.getRule());
			data.setStatus(model.getStatus());

			return data;
		}
		return null;
	}	
	
	/**
	 * 
	 * @return
	 */
	public static List<DBIpFilterModel> load() {
		Session session = HibernateLogManager.getSession();
		Criteria criteria = session.createCriteria(DBIpFilterModel.class);
		List<?> objlist = criteria.list();		
		HibernateLogManager.endSession();
		return (List<DBIpFilterModel>)objlist;
	}	

}
